const express = require('express')
const path = require('path');
const cors = require('cors')
require('dotenv').config()
const logger = require('./utils/logger')
const app = express()
const PORT = process.env.PORT || 3001

// Middleware
app.use(cors())
app.use(express.json())
app.use(express.urlencoded({ extended: true }))
app.use(express.static('public'))

// Routes
app.use('/api', require('./routes/index'))

// 设置静态资源目录为../resources/dist
app.use(express.static('../resources/dist'))

// 兜底路由：所有未匹配的请求，返回index.html（放在最后！）
app.get('*', (req, res) => {
  res.sendFile(path.join(__dirname, '../resources/dist/index.html'));
});
// Error handling middleware
app.use((err, req, res, next) => {
  console.error(err.stack)
  res.status(500).json({ message: 'Something went wrong!' })
})


// 404 handler
app.use((req, res) => {
  res.status(404).json({ message: 'Route not found' })
})

app.listen(PORT, () => {
  logger.info(`Server is running on port ${PORT}`)
  console.log(`Server is running on port ${PORT}`)
})

module.exports = app